<template>
  <el-dialog width="600px" :visible.sync="isShow" :show-close="false" class="register">
    <div class="title" slot="title">用户注册</div>
    <el-form :model="form" :rules="rules" label-width="90px" ref="form">
      <!-- 头像 -->
      <el-form-item prop="avatar" label="头像" class="upload-img">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl + '/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="xxx"
        >
          <img v-if="form.avatar" :src="baseUrl + '/' + form.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item prop="username" label="昵称">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="手机">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="form.password"></el-input>
      </el-form-item>
      <!-- 图形码 -->
      <el-form-item prop="code" label="图形码">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <img class="register-code" :src="baseUrl + codeUrl" @click="codeImgClick" alt />
          </el-col>
        </el-row>
      </el-form-item>
      <!-- 验证码 -->
      <el-form-item prop="rcode" label="验证码">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-button @click="getCode" :disabled="totalTime != 5">
              获取验证码
              <span v-if="totalTime != 5">({{totalTime}})</span>
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="isShow = false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getPhoneCode, toRegister } from "@/api/register.js";
export default {
  // watch侦听
  watch: {
    isShow(newVal) {
      if (newVal == false) {
        this.$refs.form.resetFields();
      }
    },
  },
  data() {
    return {
      totalTime: 5,
      form: {
        avatar: "", //头像地址
        username: "",
        phone: "",
        email: "",
        password: "",
        code: "", //图形码
        rcode: "", //验证码
      },
      rules: {
        avatar: [{ required: true, message: "请上传头像", trigger: "change" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "change" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的手机号"));
              }
            },
            trigger: "change",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请正确输入邮箱"));
              }
            },
            trigger: "change",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
        ],
        code: [{ required: true, message: "请输入手机号", trigger: "change" }],
        rcode: [{ required: true, message: "请输入验证码", trigger: "change" }],
      },
      isShow: false,
      imageUrl: "",
      baseUrl: process.env.VUE_APP_URL,
      codeUrl: "/captcha?type=sendsms",
    };
  },
  methods: {
    handleAvatarSuccess(res) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.form.avatar = res.data.file_path;
      // this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
    },
    xxx(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG,PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    submit() {
      this.$refs.form.validate((result) => {
        if (result) {
          //调用注册接口
          toRegister(this.form).then((res) => {
            console.log("注册成功数据", res);
            this.isShow = false;
            this.$message.success("验证成功");
          });
        } else {
          this.$message.error("验证失败");
        }
      });
    },
    codeImgClick() {
      this.codeUrl = "/captcha?type=sendsms&adasds=" + Date.now();
    },
    getCode() {
      let num = 0;
      this.$refs.form.validateField(["phone", "code"], (err) => {
        console.log(err);
        if (err == "") {
          //验证成功
          num++;
        }
      });
      if (num == 2) {
        this.totalTime--;
        let _interval = setInterval(() => {
          this.totalTime--;
          if (this.totalTime == 0) {
            this.totalTime = 5;
            //清理倒计时
            clearInterval(_interval);
          }
        }, 1000);
        getPhoneCode({
          code: this.form.code,
          phone: this.form.phone,
        }).then((res) => {
          // if (res.data.code == 200) {
          this.$message.success(res.data.data.captcha + "");
          // } else {
          // this.$message.error(res.data.message);
          // }
          console.log("验证码:", res);
        });
      } else {
        this.$message.error("请输入手机号与图形码");
      }
    },
  },
};
</script>

<style lang="less">
.register {
  .title {
    height: 53px;
    line-height: 53px;
    font-size: 14px;
    background: linear-gradient(to right, #02c3fa, #1395fa);
    font-family: Microsoft YaHei Regular, Microsoft YaHei Regular-Regular;
    font-weight: 400;
    text-align: center;
    color: #fefefe;
    letter-spacing: 0px;
  }
  .el-dialog__header {
    padding: 0;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .upload-img {
    text-align: center;
  }

  .register-code {
    width: 100%;
    height: 40px;
  }
}
</style>